import Vue from 'vue'
import Vuex from 'vuex'
//vue中使用vuex
Vue.use(Vuex);

//创建仓库
const store = new Vuex.Store({
    //要共享的数据 仓库数据
    state: {
        count: 10, 
        students:[
            {name:'zhangsan',age:20},
            {name:'lisi',age:30},
            {name:'lisi',age:50}
        ],
        conut: {
            java: 0,
            python: 0,
            php: 0
        },
        total: 0,

        shopcar: {
            vivo: {
                price: 3596,
                num: 0,
                title: 'vivo-X20Plu屏幕指纹版逆光也清晰，照亮你的美',
                imgsrc:require("../assets/images/001.jpg")
            },
            mate10plus1: {
                price: 4999,
                num: 0,
                title: '华为mate10Plus真正的人工智能芯片',
                imgsrc: require("../assets/images/002.jpg")
            },
            mate10plus2: {
                price: 4999,
                num: 0,
                title: '华为mate10Plus真正的人工智能芯片',
                imgsrc: require("../assets/images/003.jpg")
            }
        },
        money: 0,
        allnum: 0

    },
    mutations:{
        //添加学生方法
        addStu(state,newobj){  
            state.students.push(newobj);
        },
        sub(state, name) {
            state.shopcar[name].num--
                if (state.shopcar[name].num < 1) state.shopcar[name].num = 0
        },
        add(state, name) {
            state.shopcar[name].num++
        },
        addcount(state,name){
           state.conut[name]++
        }
    },
    getters:{
        fmtCount(state){
            return "*"+state.count;
        },
        //筛选出大于30的学生数据 ，相当于组件内的computed
        cstudents:(state,getters)=>{
            //getters当前vuex中getters内的数据
            console.log("getters",state,getters);
            return state.students.filter(item=>item.age>30);
        },
        total: (status, getters) => {
            status.total = 0
            let map = new Map(Object.entries(status.conut))
            for (let v of map.values()) {
                status.total += v
            }
            return status.total
        },
        allmoney: (status, getters) => {
            status.money = 0
            let map = new Map(Object.entries(status.shopcar))
            for (let v of map.values()) {
                status.money += (v.price * v.num)
            }
            return status.money
        },
        allnum: (status, getters) => {
            status.allnum = 0
            let map = new Map(Object.entries(status.shopcar))
            for (let v of map.values()) {
                status.allnum += v.num
            }
            return status.allnum
        }

    },
    actions:{
        changeStu(state,params){
            console.log('params:',params);
            setTimeout(()=>{
                state.commit("addStu",{name:'newzhangsan',age:22})
            },3000)
        }
    }
})
export {store} // 抛出对象